//
//  CallExternalProcessBehavior.m
//  BadBoy
//
//  Created by wen on 2017/4/9.
//  Copyright © 2017年 com.8xiong. All rights reserved.
//

#import "CallExternalProcessBehavior.h"
#import "BDLocationTransform.h"
@interface CallExternalProcessBehavior ()

@property (nonatomic, assign) double longitue;
@property (nonatomic, assign) double latitue;

@end

@implementation CallExternalProcessBehavior

+ (void)phoneWithPhoneNumber:(NSString *)number callFinished:(void(^)())callFinished{
    NSArray *phoneArray = [number componentsSeparatedByString:@" "];
    CallExternalProcessBehavior *behavior = [[CallExternalProcessBehavior alloc] init];
    UIView *keyView = [UIApplication sharedApplication].keyWindow;
    keyView.userInteractionEnabled = NO;
    [behavior performSelector:@selector(changePhoneButtonStatus) withObject:nil afterDelay:1.0];
    if (phoneArray.count > 1) {
        
        [keyView alertWithTitle:nil message:ASLocalizedString(@"拨打电话")type:AlertTypeSheet cancleTitle:ASLocalizedString(@"取消")otherTitle:phoneArray clickBlock:^(NSInteger index) {
            if (index > 0) {
                [behavior callPhone:phoneArray[index -1]];
                if (callFinished ) {
                    callFinished();
                }
            }
            keyView.userInteractionEnabled = YES;
        }];
    }else{
        [behavior callPhone:phoneArray.firstObject];
    }
}

- (void)changePhoneButtonStatus{
    UIView *keyView = [UIApplication sharedApplication].keyWindow;
    keyView.userInteractionEnabled = YES;
}

- (NSString *)chineseCountOfString:(NSString *)string{
    if (string.length == 0) {
        return 0;
    }
    NSString *str = @"";
    for (int i = 0; i<string.length; i++) {
        unichar c = [string characterAtIndex:i];
        if (c >=0x4E00 && c <=0x9FA5){
            //汉字
        }else{
            //英文
            str = [str stringByAppendingString:[NSString stringWithFormat:@"%c", c]];
        }
    }
    return str;
}

- (void)callPhone:(NSString *)phone{
    NSMutableString * str=[[NSMutableString alloc] initWithFormat:@"telprompt://%@",[self chineseCountOfString:phone]];
    
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:str]];
    });
}

+ (void)routeNavigationWithLongitue:(double)longitue latitue:(double)latitue{
    // BDLog(ASLocalizedString(@"选择地图进行导航"));
    
    NSMutableArray *array = [NSMutableArray arrayWithObject:ASLocalizedString(@"苹果自带地图导航")];
    if ([[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:@"baidumap://"]]) {
        [array addObject:ASLocalizedString(@"百度地图")];
    }
    if ([[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:@"iosamap://"]]) {
        [array addObject:ASLocalizedString(@"高德地图")];
    }
    CallExternalProcessBehavior *behavior = [[CallExternalProcessBehavior alloc] init];
    behavior.longitue = longitue;
    behavior.latitue = latitue;
    UIView *keyView = [UIApplication sharedApplication].keyWindow;
    keyView.userInteractionEnabled = NO;
    [keyView alertWithTitle:nil message:nil type:AlertTypeSheet cancleTitle:ASLocalizedString(@"取消")otherTitle:array clickBlock:^(NSInteger index) {
        switch (index) {
            case 1:{
                [behavior appleDaohang];
                break;
            }
            case 2:{
                if ([[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:@"baidumap://"]]) {
                    [behavior baiduDaohang];
                }else{
                    [behavior gaodeDaohang];
                }
                break;
            }
            case 3:{
                [behavior gaodeDaohang];
            }
            default:
                break;
        }
        keyView.userInteractionEnabled = YES;
    }];
}

- (void)appleDaohang{
    // BDLog(ASLocalizedString(@"苹果自带地图导航"));
    /*
     *  CLLocationCoordinate2DMake(23.1117130000, 113.3304300000) 为测试数据
     *  要从后台拿到该数据  CLLocationCoordinate2DMake([self.shopDictionary[@"latitude"] floatValue], [self.shopDictionary[@"longitude"] floatValue]);
     */
    CLLocationCoordinate2D loc = CLLocationCoordinate2DMake(self.latitue, self.longitue);
    MKMapItem *currentLocation = [MKMapItem mapItemForCurrentLocation];
    MKMapItem *toLocation = [[MKMapItem alloc] initWithPlacemark:[[MKPlacemark alloc]initWithCoordinate:loc addressDictionary:nil]];
    [MKMapItem openMapsWithItems:@[currentLocation,toLocation] launchOptions:@{MKLaunchOptionsDirectionsModeKey:MKLaunchOptionsDirectionsModeDriving,MKLaunchOptionsShowsTrafficKey:[NSNumber numberWithBool:YES]}];
}

- (void)baiduDaohang{
    // BDLog(ASLocalizedString(@"百度地图导航"));
    BDLocationTransform *locationTransform = [[BDLocationTransform alloc] initWithLatitude:self.latitue andLongitude:self.longitue];
    BDLocationTransform *newLocation = [locationTransform transformFromBDToGD];
    NSString *urlString = [[NSString stringWithFormat:@"baidumap://map/direction?origin={{我的位置}}&destination=latlng:%f,%f|name=目的地&mode=driving&coord_type=gcj02",newLocation.latitude, newLocation.longitude] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
//    NSString *urlString = [[NSString stringWithFormat:ASLocalizedString(@"baidumap://map/direction?origin={{我的位置}}&destination=latlng:%f,%f|name=目的地&mode=driving&coord_type=gcj02"),self.latitue, self.longitue] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:urlString]];
}

- (void)gaodeDaohang{
    // BDLog(ASLocalizedString(@"高德地图导航"));
    NSString *urlString = [[NSString stringWithFormat:@"iosamap://navi?sourceApplication=%@&backScheme=%@&lat=%f&lon=%f&dev=0&style=2",@"BadBoy",@"BDTEST",self.latitue, self.longitue] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:urlString]];
}


@end
